package com.sakuracard.stepdemo.service.base;

import com.sakuracard.stepdemo.mapper.BaseMapper;
import com.sakuracard.stepdemo.mapper.HomeContentMapper;
import com.sakuracard.stepdemo.model.HomeContentEntity;
import com.sakuracard.stepdemo.model.base.TransferableBaseEntity;
import com.sakuracard.stepdemo.web.model.ListResult;
import com.sakuracard.stepdemo.web.model.SearchParams;
import org.springframework.context.NoSuchMessageException;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Optional;

public class BaseServiceImpl<MAPPER extends BaseMapper<T>, T extends TransferableBaseEntity> implements BaseService<T> {
  protected final MAPPER mapper;

  public BaseServiceImpl(MAPPER mapper) {
    this.mapper = mapper;
  }

  @Override
  public ListResult<T> getList(SearchParams params) {
    int count = mapper.selectCount(params);
    List<T> list = mapper.selectList(params);
    return new ListResult<>(params.getCurrentPage(), count, (int) (double) (count / params.getPerPage()), params.getPerPage(), list);
  }

  @Override
  public T getData(int id) {
    return mapper.selectById(id);
  }

  @Override
  public boolean insertData(T entity) {
    entity.setCreatedTime(LocalDateTime.now());
    entity.setUpdatedTime(LocalDateTime.now());
    entity.setCreatedUser("admin");
    entity.setUpdatedUser("admin");
    return mapper.insert(entity) > 0;
  }

  @Override
  public boolean updateData(int id, T entity) {
    entity.setUpdatedUser("admin");
    entity.setUpdatedTime(LocalDateTime.now());
    entity.setId((int) id);
    return mapper.update(entity) == 1;
  }

  @Override
  public boolean deleteData(long id) {
    throw new NoSuchMessageException("");
  }
}
